<template>
  <div class="customer-content">
    <div class="content-header">
      <div class="content-back" @click="back">
        <el-icon><arrow-left-bold /></el-icon>
        <span>返回</span>
        <span>|</span>
      </div>
      <div class="content-title">客户详情</div>
    </div>
    <div class="content-wrapper">
      <!-- 客户信息 -->
      <customerBaseInfo :customerInfo="customerInfo" :currency-info="currencyInfo" />

      <div class="right">
        <div class="card lable-card">
          <div class="title"><span>用户标签</span>
            <div><el-button type="primary" plain v-has="['120303']" @click="openLableDialog" :disabled="!id">更新标签</el-button>
              <el-button type="primary" plain @click="openIntegral" v-has="['120305']" :disabled="!id">修改积分</el-button>
            </div>
          </div>
          <div class="lable-list" ref="lableListRef" :style="{ height: showMoreLable ? 'auto' : '82px' }">
            <span class="lable-item" v-for="item in lableList" :key="item.id">{{ item.propertyName }}:{{ item.defaultValue
            }}</span>
          </div>
          <div class="more-lable" v-show="showMoreIcon">
            <div v-show="!showMoreLable" @click="showMoreLable = true"><span>查看更多</span><span><el-icon>
                  <ArrowDown />
                </el-icon></span>
            </div>
            <div v-show="showMoreLable" @click="showMoreLable = false"><span>收起</span><span><el-icon>
                  <ArrowUp />
                </el-icon></span>
            </div>
          </div>
        </div>
        <div class="card act-card">
          <div class="title">活动类数据</div>
          <div class="act-card-content">
            <div class="col" style="margin-right: 86px;"><span class="lable">参与活动次数</span><span class="row-text">{{
              actInfo.actCountNum ?? 0 }}</span></div>
            <div class="col"><span class="lable">近一个月参与次数</span><span class="row-text">{{ actInfo.actNealyMouthCountNum ??
              0
            }}</span></div>
          </div>
        </div>
        <div class="card mall-card">
          <div class="title">商城类数据</div>
          <div class="mall-card-content">
            <div class="tabs">
              <div class="tab" :class="{ 'active-tab': currentMall.id == item.id }" v-for="item in preMallList"
                @click="mallItemClick(item)">{{ item.mallName }}</div>
              <div class="next-box" v-if="nextMallList.length">
                <span class="tri-box" v-show="showMoreMall"></span>
                <span class="more-text" @click="showMoreMall = !showMoreMall"
                  :style="{ color: currentMoreMall.mallName ? 'var(--el-color-primary)' : '#666' }">{{
                    currentMoreMall.mallName
                    ?? '更多' }}<el-icon style="margin-left:4px" v-show="!showMoreMall">
                    <ArrowDown />
                  </el-icon>
                  <el-icon style="margin-left:4px" v-show="showMoreMall">
                    <ArrowUp v-show="showMoreMall" />
                  </el-icon>
                </span>
                <div class="next-content" v-show="showMoreMall">
                  <div class="tab more-tab" v-for="item in nextMallList" style="border-bottom: none;"
                    @click="moreItemClick(item)" :class="{ 'active-tab': currentMoreMall.id == item.id }">{{ item.mallName
                    }}
                  </div>
                </div>
              </div>
            </div>
            <el-row style="margin-top: 16px;z-index: 0;">
              <el-col :span="8" style="margin-bottom: 12px;">
                <span class="lable">积分类型:</span>
                <span class="row-text">{{ mallInfo.currencyName ?? '--' }}</span>
              </el-col>
              <el-col :span="8">
                <span class="lable">累计购买次数:</span>
                <span class="row-text">{{ mallInfo.countNum ?? '--' }}</span>
              </el-col><el-col :span="8">
                <span class="lable">累计消费{{ mallInfo.currencyName ?? "" }}/金额:</span>
                <span class="row-text">{{ mallInfo.countCurrency ?? '--' }}/￥{{
                  mallInfo.countMoney ? Number(((mallInfo.countMoney) / 100).toFixed(2)) : "0" }}</span>
              </el-col><el-col :span="8">
                <span class="lable">近1个月购买次数:</span>
                <span class="row-text">{{ mallInfo.nealyMouthCountNum ?? '--' }}</span>
              </el-col><el-col :span="8">
                <span class="lable">最爱购买商品分类:</span>
                <span class="row-text">{{ mallInfo.favoriteProductCategoryName ?? '--' }}</span>
              </el-col>
            </el-row>
          </div>
        </div>
        <div class="card address-card">
          <div class="title">收货地址</div>
          <div class="address-div">
            <table class="address-table">
              <tr>
                <th>收货人</th>
                <th>手机号</th>
                <th>详细地址</th>
              </tr>
              <tr v-for="item in addressList" :key="item.id">
                <td>
                  <span><el-tag v-if="item.defaultType" class="default-tag" effect="dark">默认</el-tag>{{ item.recipientName
                  }}</span>
                </td>
                <td>
                  <span>{{ item.recipientMobileNumber }}</span>
                </td>
                <td>
                  <span>{{ (item.province || '') + (item.city || '') + (item.area || '') + (item.town || '') +
                    (item.detailedAddress || '')
                  }}</span>
                </td>
              </tr>
              <tr v-if="!addressList.length">
                <td colspan="3">暂无数据</td>
              </tr>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- 修改积分 -->
  <add-integral @cancel="integralDialog = false" @confirm="updateIntegral" :showDialog="integralDialog"
    :modelData="integralData" />
  <!-- 变更标签 -->
  <el-dialog title="变更标签" v-model="lableDialog" width="460px" :before-close="closeLableDialog">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
      <el-form-item label="标签" prop="tagCode">
        <el-select v-model="formData.tagCode" @change="tagChange" placeholder="请选择标签" style="width: 100%" filterable
          clearable>
          <el-option v-for="item in userGroupPropertyList" :key="item.propertyKey" :label="item.propertyName"
            :value="item.propertyKey">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="值" prop="tagValue">
        <!-- 数字 -->
        <div v-if="propertyType == 0">
          <el-input-number v-model="formData.tagValue" :min="0" :max="99999999" controls-position="right" />
        </div>
        <!-- 字符串 -->
        <div v-if="propertyType == 1">
          <el-input v-model.trim="formData.tagValue" type="text" maxlength="15" :show-word-limit="true"
            placeholder="请填写值">
          </el-input>
        </div>
        <!-- 时间 -->
        <div v-if="propertyType == 3">
          <el-date-picker v-model="formData.tagValue" type="datetime" placeholder="请选择时间" format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss" />
        </div>

        <!-- 枚举 -->
        <div v-if="propertyType == 4">
          <el-select v-model="formData.tagValue" placeholder="请选择">
            <el-option v-for="item in enumerationList" :key="item.k" :label="item.v" :value="item.k">
            </el-option>
          </el-select>
        </div>
      </el-form-item>
      <el-form-item label="添加动作" prop="actionTypeEnum">
        <el-radio-group v-model="formData.actionTypeEnum">
          <el-radio-button v-for="item in actionTypeEnumList" :key="item.id" :label="item.id">{{ item.name
          }}</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="过期时间">
        <el-date-picker v-model="formData.expireTime" type="datetime" placeholder="选择日期" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeLableDialog">取 消</el-button>
        <el-button type="primary" @click="updateLabel">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template> 
<script lang="ts" setup>
import CustomerApi from "@/api/customerApi";
import AddIntegral from "./component/addIntegral.vue";
import customerBaseInfo from './component/customerBaseInfo.vue';
const integralDialog = ref(false)
const updateIntegral = () => {
  getCurrencyInfo()
  getInfo()
}
const customerInfo = ref({ id: "", unionId: "", nickName: "", phone: "" })

const integralData = ref()
const route = useRoute()
const lableList = ref([])
//当前客户id
const id = ref(route.params.id)
//获取当前客户信息
const getInfo = async () => {
  const res = await CustomerApi.getInfo({ id: route.params.id })
  if (res.code == 200) {
    if (res.payload) {
      id.value = res.payload.id
      customerInfo.value = res.payload
      lableList.value = res.payload.properties || []
      nextTick(() => {
        if (lableListRef.value.scrollHeight > 82) {
          showMoreIcon.value = true
        } else {
          showMoreIcon.value = false
        }
      })
    }
  }
}
const addressList = ref([])
//当前客户收货地址
const getAddressByUserId = async () => {
  if (id.value) {
    const res = await CustomerApi.getAddressByUserId({ id: id.value })
    if (res.code == 200) {
      if (res.payload) {
        addressList.value = res.payload
      }
    }
  } else {
    addressList.value = []
  }

}
const openIntegral = () => {
  const data = sessionStorage.getItem('currentCustomer') || '{}'
  integralData.value = JSON.parse(data)
  integralDialog.value = true
}
const lableListRef = ref()
const showMoreLable = ref(false)
const showMoreIcon = ref(false)
const formRef = ref()
const formData = reactive({
  actionTypeEnum: "GENERATE",
  tagValue: "",
  tagCode: "",
  expireTime: "",
})
const userGroupPropertyList = ref([])
const rules = {
  tagCode: [
    {
      required: true,
      message: "请选择标签",
      trigger: "change",
    },
  ],
  tagValue: [
    {
      required: true,
      message: "请输入值",
      trigger: "blur",
    },
  ],
}
const actionTypeEnumList = [
  { id: "GENERATE", name: "生成" },
  { id: "COVER", name: "覆盖" },
  // { id: "CUMULATIVE", name: "累加" },
  // { id: "SUBTRACT", name: "累减" },
]
const propertyType = ref(1)
const enumerationList = ref([])
const lableDialog = ref(false)
const closeLableDialog = () => {
  formRef.value.resetFields();
  formData.actionTypeEnum = 'GENERATE'
  formData.expireTime = ''
  formData.tagCode = ''
  formData.tagValue = ''
  lableDialog.value = false
}
const tagChange = (val: any) => {
  formData.tagValue = ""
  let tagItem = userGroupPropertyList.value.find(
    (item) => (item.propertyKey == val)
  )
  propertyType.value = tagItem.propertyType
  // 4是枚举类型
  if (propertyType.value == 4) {
    enumerationList.value = JSON.parse(tagItem.enumerateValue);
  }
}
const updateLabel = () => {
  saveLable()
}

const openLableDialog = () => {
  getPropertyList()
  lableDialog.value = true
}
const getPropertyList = async () => {
  let params = {
    currentPage: -1,
    showCount: 9999,
  };
  let rs = await CustomerApi.attributeList(params);
  if (rs.code == 200) {
    userGroupPropertyList.value = rs.payload;
  }
}

const saveLable = async () => {
  const params = {
    userId: id.value,
    actionTypeEnum: formData.actionTypeEnum,
    tagValue: propertyType.value == 3 ? Date.parse(formData.tagValue) : formData.tagValue,
    tagCode: formData.tagCode,
    expireTime: formData.expireTime,
  };
  if (params.expireTime) {
    params.expireTime = new Date(params.expireTime).getTime();
  }
  let rs = await CustomerApi.propertyChange(params);
  if (rs.code == 200) {
    ElMessage.success("变更标签成功");
    closeLableDialog();
    getInfo()
  }

}

const currencyInfo = ref([])
//获取积分信息
const getCurrencyInfo = async () => {
  if (id.value) {
    const res = await CustomerApi.getCurrencyInfo({ id: id.value })
    if (res.code == 200) {
      if (res.payload) {
        currencyInfo.value = res.payload
      }
    }
  } else {
    currencyInfo.value = []
  }

}
const mallList = ref([])
const preMallList = computed(() => {
  return mallList.value.slice(0, 5)
})
const nextMallList = computed(() => {
  return mallList.value.slice(5)
})
const showMoreMall = ref(false)
const currentMall = ref({})
const currentMoreMall = ref({})
const mallInfo = ref({})
const getMallList = async () => {
  if (id.value) {
    const res = await CustomerApi.getMallList({ id: id.value})
    if (res.code == 200) {
      if (res.payload) {
        mallList.value = res.payload
        if (mallList.value?.[0]) {
          getMallInfo(mallList.value[0].id)
          currentMall.value=mallList.value[0]
        }
      }
    }
  } else {
    mallInfo.value = {}
    mallList.value = []
  }

}

const getMallInfo = async (mallId: number) => {
  if (id.value) {
    const res = await CustomerApi.getMallInfo({ userId: id.value, mallId: mallId })
    if (res.code == 200) {
      if (res.payload) {
        mallInfo.value = res.payload
      }
    }
  } else {
    mallInfo.value = {}
  }

}
const actInfo = ref({ actCountNum: 0, actNealyMouthCountNum: 0 })
const getActInfo = async () => {
  if (id.value) {
    const res = await CustomerApi.getActInfo({ id: id.value })
    if (res.code == 200) {
      if (res.payload) {
        actInfo.value = res.payload
      }
    }
  } else {
    actInfo.value = { actCountNum: 0, actNealyMouthCountNum: 0 }
  }

}
const moreItemClick = (item) => {
  getMallInfo(item.id)
  currentMoreMall.value = item
  currentMall.value = {}
  showMoreMall.value = false
}
const mallItemClick = (item) => {
  getMallInfo(item.id)
  currentMall.value = item
  currentMoreMall.value = {}
  showMoreMall.value = false
}
const initData = async () => {
  await getInfo()
  getAddressByUserId()
  getCurrencyInfo()
  getMallList()
  getActInfo()
}
const store = useStore()
const insId = computed(() => store.state.insId.insId)
watch(insId, () => {
  initData()
}, { deep: true })
onMounted(() => {
  initData()
})

const router = useRouter()
const back = () => {
  sessionStorage.removeItem('currentCustomer')
  router.back()
}
</script>

<style lang="scss" scoped>
.customer-content {
  width: 100%;
}

.content-header {
  padding: 0 30px;
  box-sizing: border-box;
  height: 60px;
  line-height: 60px;
  font-size: 20px;
  background: #fff;
  display: flex;
  align-items: center;
  box-shadow: 0px 1px 12px 0px rgba(0, 0, 0, 0.06),
    inset 0px -1px 0px 0px #ebedf0;

  .content-title {
    font-weight: 700;
    color: #303133;
    flex: 1;
  }

  .content-back {
    width: 80px;
    display: flex;
    font-size: 14px;
    color: #606265;
    align-items: center;
    cursor: pointer;

    :deep(.el-icon) {
      margin-right: 7px;
      color: #606265;
    }

    span {
      margin-right: 10px;
    }
  }
}

.content-wrapper {
  height: calc(100vh - 140px);
  display: flex;
  box-sizing: border-box;
}

.title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #303133;
  font-size: 18px;
  font-weight: 700;
}

.right {
  flex: 1;
  height: 100%;
  overflow-y: auto;

  .card {
    margin: 20px;
    margin-bottom: 6px;
    padding: 20px;
    box-sizing: border-box;
    border-radius: 4px;
    box-shadow: 0px 2px 12px 0px rgba(0, 0, 0, 0.1);
  }
}

.lable-card {
  .lable-list {
    display: flex;
    align-items: flex-start;
    flex-wrap: wrap;
    overflow: hidden;
  }

  .lable-item {
    margin-top: 8px;
    margin-right: 12px;
    padding: 6px 8px;
    background: #E9EEFF;
    border-radius: 2px;
  }

  .more-lable {
    display: flex;
    justify-content: center;
    margin-top: 20px;
    text-align: center;

    &>div {
      color: var(--el-color-primary);
      cursor: pointer;
    }
  }
}

.act-card {
  .act-card-content {
    margin-top: 20px;
    display: flex;
  }
}

.mall-card {
  .mall-card-content {
    margin-top: 16px;

    .tabs {
      display: flex;
    }

    .tab {
      flex-shrink: 0;
      padding: 4px 0;
      margin-right: 24px;
      font-size: 16px;
      color: #666;
      cursor: pointer;
      transition: all 0.2s;
      border-bottom: 3px solid transparent;
    }

    .next-box {
      position: relative;

      .more-text {
        padding: 4px 0;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 16px;
        color: #666;
        cursor: pointer;
      }

      .tri-box {
        z-index: 2;
        position: absolute;
        top: 30px;
        left: 50%;
        display: inline-block;
        width: 8px;
        height: 8px;
        background-color: #fff;
        transform: rotate(45deg);
        border: 1px solid rgba(0, 0, 0, 0.1);
        border-bottom-color: transparent;
        border-right-color: transparent;
      }
    }

    .next-content {
      overflow: auto;
      min-width: 240px;
      max-height: 300px;
      z-index: 1;
      position: absolute;
      right: -60px;
      top: 36px;
      background-color: #fff;
      box-shadow: 0px 2px 12px 0px rgba(0, 0, 0, 0.1);

      .more-tab {
        margin: 8px 20px;
      }
    }

    .active-tab {
      color: var(--el-color-primary);
      border-bottom: 3px solid var(--el-color-primary);
    }
  }

  
}
.address-card{

  .address-div {
    margin-top: 20px;
    height: 466px;
    overflow-y: auto;
    overflow-x: hidden;
  }

  .address-table {
    width: 100%;
    overflow-x: auto;
    overflow-y: hidden;
    border: 1px solid #999;
    border-collapse: collapse;

    tr,
    th,
    td {
      border: 1px solid #999;
    }

    th,
    td {
      text-align: center;
      padding: 10px;
      // padding: 10px 70px;
      min-width: 200px;
      box-sizing: border-box;

      >span {
        position: relative;
        min-width: 44px;
        display: inline-block;
      }

      .default-tag {
        position: absolute;
        left: -48px;
      }
    }
  }
}

.lable {
  color: #666666;
  font-size: 15px;
}

.row-text {
  margin-left: 12px;
  font-size: 15px;
  font-weight: 500;
  color: #333333;
}
</style>
